package cn.ibdsr.human.util;

import org.springframework.util.StringUtils;

import java.util.Random;

/**
 * Token工具类
 * @author: chenglx
 * @date: 2021-03-23
 * @lastModified:
 *
 * Date           Author               Description
 * ------------------------------------------------------
 * 2021-03-23     chenglx                创建
 */
public class TokenUtils {

    private static char[] charTable = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_".toCharArray();
    private static int charCount = charTable.length;
    private static Random random = new Random();
    private static int defaultTokenLen = 32;

    /**
     * 产生随机token
     * @param seed 种子字符串
     * @param tokenLen 生成的token长度
     * @return
     */
    public static String generateToken(String seed, int tokenLen) {
        // 初始字符串检查
        if (StringUtils.isEmpty(seed)) {
            seed = "family-memory";
        }
        seed += System.nanoTime();
        byte[] seedBytes = seed.getBytes();
        // 长度检查
        if (tokenLen < 1) {
            tokenLen = defaultTokenLen;
        }
        // 生成随机字符串
        char[] token = new char[tokenLen];
        for (int i = 0; i < tokenLen; ++i) {
            int idx = (random.nextInt(256) ^ seedBytes[random.nextInt(seedBytes.length)]) % charCount;
            token[i] = charTable[idx];
        }
        return new String(token);
    }


    public static void main(String[] args) {
        System.out.println("test:" + (0^0) + ", " + (0^1) + ", " + (1^0)  + ", " + (1^1));
        int[] a = new int[9];
        System.out.println("token: " + generateToken("abc", 16));
//        System.out.println("token:" + TokenUtil.encodedString(System.currentTimeMillis() + "", "1236"));

    }

}
